<template>
   <div class="app-container">
      <div class="filter-wrap">
         <div>请选择服务区：</div>
         <el-tree-select
            v-model="serviceId"
            :data="deptTreeData"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            :render-after-expand="false"
            show-checkbox
            value-key="id"
            check-strictly
            placeholder="请选择归属组织"
            class="with-300"
            disabled
         />
      </div>
      
      <h1>车辆品牌分类设置</h1>
      <div class="brand-wrap">
         <el-card shadow="never" class="left-box">
            <template #header>
               <div class="card-header">
                  <span>品牌</span>
               </div>
            </template>

            <div class="text-item">
               <div v-for="(item,index) in brandValue" :key="index" class="order-list">
                  <div class="title">
                     {{item.order }}
                  </div>

                  <div class="brand-list">
                     <span v-for="(obj,idx) in item?.list"
                        :key="idx"
                        @click="selectBrand(obj)"
                        :class="isLeftActive == obj?.value ? 'current' : ''"
                     >{{ obj.label }}</span>
                  </div>
               </div>
            </div>
         </el-card>

         <div class="right-box">
            <div class="level mb-20">
               <div>
                  <div class="arrow-box right" @click="addBrand('high')" :class="brandInfo.value ? '' : 'not-click'"><el-icon><ArrowRight /></el-icon></div>
                  <div class="arrow-box" @click="deleteBrand('high')" :class="brandHigh?.length && brandHighInfo?.value ? '' : 'not-click'"><el-icon><ArrowLeft /></el-icon></div>
               </div>
               <el-card shadow="never">
                  <template #header>
                     <div class="card-header">
                        <span>高端品牌</span>
                     </div>
                  </template>
                  
                  <div class="brand-list">
                     <span v-for="(obj,idx) in brandHigh"
                        :key="idx"
                        @click="selectCar(obj,'high')"
                        :class="isHighActive == obj?.value ? 'current' : ''"
                     >{{ obj.label }}</span>
                  </div>
               </el-card>
            </div>
            
            <div class="level mb-20">
               <div>
                  <div class="arrow-box right" @click="addBrand('middle')" :class="brandInfo.value ? '' : 'not-click'"><el-icon><ArrowRight /></el-icon></div>
                  <div class="arrow-box" @click="deleteBrand('middle')" :class="brandMiddle?.length && brandMiddleInfo?.value ? '' : 'not-click'"><el-icon><ArrowLeft /></el-icon></div>
               </div>
               <el-card shadow="never">
                  <template #header>
                     <div class="card-header">
                        <span>中端品牌</span>
                     </div>
                  </template>

                  <div class="brand-list">
                     <span v-for="(obj,idx) in brandMiddle"
                        :key="idx"
                        @click="selectCar(obj,'middle')"
                        :class="isMiddleActive == obj?.value ? 'current' : ''"
                     >{{ obj.label }}</span>
                  </div>
               </el-card>
            </div>
            
            <div class="level">
               <div>
                  <div class="arrow-box right" @click="addBrand('low')" :class="brandInfo.value ? '' : 'not-click'"><el-icon><ArrowRight /></el-icon></div>
                  <div class="arrow-box" @click="deleteBrand('low')" :class="brandLow?.length && brandLowInfo?.value ? '' : 'not-click'"><el-icon><ArrowLeft /></el-icon></div>
               </div>
               <el-card shadow="never">
                  <template #header>
                     <div class="card-header">
                        <span>低端品牌</span>
                     </div>
                  </template>
                  <div class="brand-list">
                     <span v-for="(obj,idx) in brandLow"
                        :key="idx"
                        @click="selectCar(obj,'low')"
                        :class="isLowActive == obj?.value ? 'current' : ''"
                     >{{ obj.label }}</span>
                  </div>
               </el-card>
            </div>
         </div>
      </div>
      <div class="mt-30 btn-wrap">
         <el-button type="primary" @click="submitForm" v-hasPermi="['system:serviceArea:grade']">保存</el-button>
      </div>
      
   </div>
</template>

<script setup name="BrandGrade">
import useUserStore from '@/store/modules/user'
import { getBrandCategoryList,setBrandCategory } from "@/api/system/service";
const { proxy } = getCurrentInstance();
const route = useRoute();
const serviceId = ref(Number(route.query?.serviceId) || "")
const brandValue = ref([]);
const brandHigh = ref([]);
const brandMiddle = ref([]);
const brandLow = ref([]);
const brandInfo = ref({});
const brandHighInfo = ref({});
const brandMiddleInfo = ref({});
const brandLowInfo = ref({});
let arrList = reactive([]);
const isLeftActive = ref("");
const isHighActive = ref("");
const isMiddleActive = ref("");
const isLowActive = ref("");
const { car_brand} = proxy.useDict("car_brand");
const queryParams = reactive({
   pageNum: 1,
   pageSize: 10
});
const getList = () =>{
   const parmas = {
      ...queryParams,
      serviceId:serviceId.value
   }
   getBrandCategoryList(parmas).then(response => {
      if(response.code == 200){
         const data = response?.rows?.map(ele => {
            return {
               carBrandCategory:ele?.carBrandCategory,
               label:ele?.carBrandName,
               value:ele?.carBrandCode
            }
         }) || []
         brandHigh.value = data.filter(ele => ele.carBrandCategory === "high") || [];
         brandMiddle.value = data.filter(ele => ele.carBrandCategory === "middle") || [];
         brandLow.value = data.filter(ele => ele.carBrandCategory === "low") || [];
      }
      else{
         proxy.$modal.msgError(response?.msg || "获取配置信息失败，请稍后重试!");
      }
   })
}

/** 提交按钮 */
const submitForm = () =>{
   if(!brandHigh.value?.length && !brandMiddle.value?.length && !brandLow.value?.length){
      proxy.$modal.msg("请选择车型品牌分类");
      return
   }
   const parmas = {
      serviceId:serviceId.value,
      high:brandHigh.value.map(ele => ele.value),
      middle:brandMiddle.value.map(ele => ele.value),
      low:brandLow.value.map(ele => ele.value)
   }
   setBrandCategory(parmas).then(response => {
      if(response.code == 200){
         proxy.$modal.msgSuccess("配置成功");
         const obj = { path: "/system/serviceArea" };
         proxy.$tab.closeOpenPage(obj);
      }else{
         proxy.$modal.msgError(response?.msg || "配置失败，请稍后重试!");
      }
   });
}

const selectBrand = (item) =>{
   if(item.value == isLeftActive.value){
      isLeftActive.value = "";
      brandInfo.value = {}
   }
   else{
      isLeftActive.value = item.value;
      brandInfo.value = item
   }
}
const selectCar = (item,type) =>{
   if(type == "high"){
      if(isHighActive.value == item.value){
         isHighActive.value = "";
         brandHighInfo.value = {}
      }
      else{
         isHighActive.value = item.value;
         brandHighInfo.value = item 
      }
   }
   else if(type == "middle"){
      if(isMiddleActive.value == item.value){
         isMiddleActive.value = "";
         brandMiddleInfo.value = {}
      }
      else{
         isMiddleActive.value = item.value;
         brandMiddleInfo.value = item
      }
   }
   else if(type == "low"){
      if(isLowActive.value == item.value){
         isLowActive.value = "";
         brandLowInfo.value = {}
      }
      else{
         isLowActive.value = item.value;
         brandLowInfo.value = item
      }
   }
}

const addBrand = (type) =>{
   if(brandInfo.value?.value){
      if(type == "high"){
         handleRepeat(brandHigh.value)
      }
      else if(type == "middle"){
         handleRepeat(brandMiddle.value)
      }
      else if(type == "low"){
         handleRepeat(brandLow.value)
      }
   }
}

const deleteBrand = (type) =>{
   if(type == "high"){
      if(brandHighInfo.value?.value){
         brandHigh.value.splice(brandHigh.value.findIndex(ele => ele.value === brandHighInfo.value?.value),1);
         brandHighInfo.value = {}
      }
   }
   else if(type == "middle"){
      if(brandMiddleInfo.value?.value){
         brandMiddle.value.splice(brandMiddle.value.findIndex(ele => ele.value === brandMiddleInfo.value?.value),1)
         brandMiddleInfo.value = {}
      }
   }
   else if(type == "low"){
      if(brandLowInfo.value?.value){
         brandLow.value.splice(brandLow.value.findIndex(ele => ele.value === brandLowInfo.value?.value),1)
         brandLowInfo.value = {}
      }
   }
}

const handleRepeat = (arr) => {
   if(arr.findIndex(ele => ele.value === brandInfo.value?.value) == -1){
      arr.push(brandInfo.value);
      brandInfo.value = {}
      isLeftActive.value = "";
   }
   else{
      proxy.$modal.msg("已存在该品牌,请勿重复添加!");
      return
   }
}

const handleData = (newVal)=>{
   let arrBrand = JSON.parse(JSON.stringify(newVal));
   arrBrand.map(ele => {
      if(arrList?.length){
         const index = arrList.findIndex(item => item.order === ele.remark);
         if(index == -1){
            arrList.push({
               order:ele.remark,
               list:[ele]
            })
         }
         else{
            arrList[index].list.push(ele)
         }
      }
      else{
         arrList.push({
            order:ele.remark,
            list:[ele]
         })
      }
      return arrList
   })
   brandValue.value = arrList.sort((a,b)=>{return a.order.localeCompare(b.order)})
}

const brande = computed(()=>{
   return car_brand.value
})

const deptTreeData = computed(()=>{
   return useUserStore().deptTreeData
})

watch(() => brande.value,(newVal, oldVal)=>{
   if(newVal?.length){
      handleData(newVal)
   }
},
{
   deep: true,
   immediate: true
})
getList()
</script>

<style lang="scss" scoped>
   .filter-wrap{
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      color: #666
   }
   .brand-wrap{
      display: flex;
      justify-content: space-between;
      // align-items: flex-start;
      .left-box{
         width: 50%;
         // height: 100%;
         .text-item{
            .order-list{
               display: flex;
               align-items: flex-start;
               .title{
                  margin-right: 20px;
                  color: #f89c34;
                  font-weight: bold;
                  font-size: 20px
               }
            }
            .order-list:not(:last-child){
               margin-bottom: 30px;
            }
         }
      }
      .right-box{
         width: 50%;
         .level{
            display: flex;
            align-items: center;
            height: 31.3%;
            .el-card{
               flex:1;
               height: 100%;
            }
            .el-card:not(:last-child){
               margin-bottom: 20px;
            }
            .arrow-box{
               display: flex;
               align-items: center;
               justify-content: space-between;
               margin: 0 50px;
               padding: 6px;
               border: 1px solid #666;
               cursor: pointer;
               margin-bottom: 20px
            }
            .not-click{
               cursor: not-allowed
            }
            .right{
               border-color: #f89c34;
               .el-icon{
                  color: #f89c34;
               }
            }
         }
      }
      .brand-list{
         flex:1;
         span{
            font-size: 14px;
            display: inline-block;
            padding: 4px 10px;
            margin-right: 10px;
            margin-bottom: 10px;
            cursor: pointer;
         }
         .current{
            border-radius: 5px;
            background:#f89c34;
            color: #fff;
         }           
      }
      
   }
   .btn-wrap{
      text-align: center
   }
</style>
